package com.mt.demo.controller;

import com.mt.demo.domain.AjaxResult;
import com.mt.demo.domain.MtMeeting;
import com.mt.demo.domain.MtMember;
import com.mt.demo.domain.SysUser;
import com.mt.demo.manager.MeetingRoomManager;
import com.mt.demo.manager.MeetingUserManager;
import com.mt.demo.service.IMtMeetingService;
import com.mt.demo.service.IMtMemberService;
import com.mt.demo.service.ISysUserService;
import com.mt.demo.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

@RestController
@RequestMapping("/meeting/room")
public class MeetingRoomController extends BaseController {

    @Autowired
    private IMtMeetingService meetingService;

    @Autowired
    private IMtMemberService memberService;

    @Autowired
    private MeetingRoomManager meetingRoomManager;

    @Autowired
    private MeetingUserManager meetingUserManager;
    @Autowired
    private ISysUserService userService;

    /**
     * 创建会议房间
     */
    @PostMapping("/create")
    public AjaxResult createMeeting(@RequestBody MtMeeting request) {
        // 创建会议
        request.setMeetingNo(generateMeetingId());
        request.setCreateTime(DateUtils.getNowDate());
        request.setStatus("ing"); // ing-进行中 ed-已结束

        int result = meetingService.insertMtMeeting(request);
        if (result > 0) {
            // 添加创建者为主持人
            MtMember creator = new MtMember();
            creator.setMeetingId(request.getMeetingId());
            creator.setMeetingName(request.getMeetingName());
            creator.setUserId(request.getHostUserId());
            creator.setNickName(request.getHostNickName());
            creator.setFirstJoin(DateUtils.getNowDate());
            creator.setJoinTimes(1L);
            // master-主持人 guest-参会者
            creator.setIdentity("master");
            memberService.insertMtMember(creator);
            
            return AjaxResult.success("会议创建成功", request);
        }
        return AjaxResult.error("会议创建失败");
    }

    /**
     * 加入会议房间（HTTP方式预加入，获取会议信息）
     */
    @PostMapping("/join")
    public AjaxResult joinMeeting(@RequestBody JoinMeetingRequest request) {
        // 检查会议是否存在
        MtMeeting meeting = meetingService.selectMtMeetingByMeetingId(request.getMeetingId());
        if (meeting == null) {
            return AjaxResult.error("会议不存在");
        }

        // 检查会议状态
        if (!"ing".equals(meeting.getStatus())) {
            return AjaxResult.error("会议已结束");
        }

        // 检查用户是否已经是会议成员
        MtMember existingMember = new MtMember();
        existingMember.setMeetingId(request.getMeetingId());
        existingMember.setUserId(request.getUserId());
        List<MtMember> members = memberService.selectMtMemberList(existingMember);

        MtMember member;
        if (members.isEmpty()) {
            // 根据用户ID查询用户信息
            SysUser sysUser = userService.selectUserById(request.getUserId());
            // 根据会议id查询会议信息
            MtMeeting existMeeting = meetingService.selectMtMeetingByMeetingId(request.getMeetingId());
            // 添加新成员
            member = new MtMember();
            member.setMeetingId(existMeeting.getMeetingId());
            member.setMeetingName(existMeeting.getMeetingName());
            member.setUserId(sysUser.getUserId());
            member.setNickName(sysUser.getNickName());
            member.setFirstJoin(DateUtils.getNowDate());
            // master-主持人 guest-参会者
            member.setIdentity("guest");
            memberService.insertMtMember(member);
        } else {
            member = members.get(0);
        }

        // 返回会议信息和连接参数
        Map<String, Object> response = new HashMap<>();
        response.put("meeting", meeting);
        response.put("member", member);
        Map<String, String> socketParams = new HashMap<>();
        socketParams.put("roomId", meeting.getMeetingId().toString());
        socketParams.put("userId", request.getUserId().toString());
        socketParams.put("socketUrl", "http://localhost:9092");
        response.put("socketParams", socketParams);


        response.put("onlineCount", meetingRoomManager.getRoomOnlineCount(meeting.getMeetingId().toString()));
        response.put("onlineUsers", meetingUserManager.getOnlineUsers(meeting.getMeetingId().toString()));

        return AjaxResult.success("获取会议信息成功", response);
    }

    /**
     * 结束会议
     */
    @PostMapping("/end/{meetingId}")
    public AjaxResult endMeeting(@PathVariable Long meetingId, @RequestParam String userId) {
        MtMeeting meeting = meetingService.selectMtMeetingByMeetingId(meetingId);
        if (meeting == null) {
            return AjaxResult.error("会议不存在");
        }

        // 检查是否是主持人
        MtMember hostMember = new MtMember();
        hostMember.setMeetingId(meetingId);
        hostMember.setUserId(Long.parseLong(userId));
        hostMember.setIdentity("master");
        List<MtMember> hosts = memberService.selectMtMemberList(hostMember);
        
        if (hosts.isEmpty()) {
            return AjaxResult.error("只有主持人可以结束会议");
        }

        // 更新会议状态
        meeting.setStatus("0");
        meeting.setEndTime(DateUtils.getNowDate());
        meetingService.updateMtMeeting(meeting);

        // 通知所有在线用户会议结束
        meetingRoomManager.getRoomClients(meetingId.toString()).forEach(client -> {
            client.sendEvent("meetingEnded", "会议已结束");
            client.disconnect();
        });

        return AjaxResult.success("会议已结束");
    }

    /**
     * 获取会议详情
     */
    @GetMapping("/detail/{meetingId}")
    public AjaxResult getMeetingDetail(@PathVariable Long meetingId) {
        MtMeeting meeting = meetingService.selectMtMeetingByMeetingId(meetingId);
        if (meeting == null) {
            return AjaxResult.error("会议不存在");
        }

        // 获取会议成员列表
        MtMember memberQuery = new MtMember();
        memberQuery.setMeetingId(meetingId);
        List<MtMember> allMembers = memberService.selectMtMemberList(memberQuery);

        Map<String, Object> response = new HashMap<>();
        response.put("meeting", meeting);
        response.put("allMembers", allMembers);
        response.put("onlineMembers", meetingUserManager.getOnlineUsers(meetingId.toString()));
        response.put("onlineCount", meetingRoomManager.getRoomOnlineCount(meetingId.toString()));
        response.put("screenSharingUser", meetingRoomManager.getScreenSharingUser(meetingId.toString()));

        return AjaxResult.success(response);
    }

    /**
     * 获取用户的会议列表
     */
    @GetMapping("/list/{userId}")
    public AjaxResult getUserMeetings(@PathVariable Long userId) {
        MtMember memberQuery = new MtMember();
        memberQuery.setUserId(userId);
        List<MtMember> userMembers = memberService.selectMtMemberList(memberQuery);

        List<Map<String, Object>> meetings = new ArrayList<>();
        for (MtMember member : userMembers) {
            MtMeeting meeting = meetingService.selectMtMeetingByMeetingId(member.getMeetingId());
            if (meeting != null) {
                Map<String, Object> meetingInfo = new HashMap<>();
                meetingInfo.put("meeting", meeting);
                meetingInfo.put("memberInfo", member);
                meetingInfo.put("onlineCount", meetingRoomManager.getRoomOnlineCount(meeting.getMeetingId().toString()));
                meetings.add(meetingInfo);
            }
        }

        return AjaxResult.success(meetings);
    }
    /**
     * 根据当前时间戳生成会议号
     * @return 生成的会议号字符串
     */
    public static String generateMeetingId() {
        // 获取当前时间戳
        long timestamp = Instant.now().toEpochMilli();

        // 将时间戳转换为 LocalDateTime
        LocalDateTime dateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault());

        // 定义会议号的格式（例如：yyyyMMddHHmmss + 时间戳的后6位）
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String formattedDate = dateTime.format(formatter);

        // 取时间戳的后6位作为唯一标识
        String uniqueSuffix = Long.toString(timestamp, 36).substring(8); // 转换为36进制并取后几位

        // 拼接生成会议号
        return formattedDate + uniqueSuffix;
    }

    public static class JoinMeetingRequest {
        private Long meetingId;
        private Long userId;

        // Getters and setters
        public Long getMeetingId() { return meetingId; }
        public void setMeetingId(Long meetingId) { this.meetingId = meetingId; }
        public Long getUserId() { return userId; }
        public void setUserId(Long userId) { this.userId = userId; }
    }
}
